package com.qdone;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 启动器
 *  Session集群方案
 *    1.A.@EnableRedisHttpSession+spring-session-data-redis:配置session采用redis同步
 *     自定义指定，spring-session的参数，请参照如下方式:
 *      @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800,redisNamespace="spring_session")
 *     B.引入 spring-session-data-redis架包，在application.properties里面配置：
 *        spring.session.store-type=REDIS
 *        spring.session.timeout=60
 *        spring.session.redis.cleanup-cron=0 * * * * *
 *        spring.session.redis.flush-mode=on-save
 *        spring.session.redis.namespace=boot:simple:spring:session
 *    2.@EnableRedissonHttpSession+spring-session:配置redisson同步session
 *  Profile多环境启动方案：
 *    1.直接运行jar,指定uat环境运行[java -jar -Dspring.profiles.active=test boot-simple.jar]
 *    2.Eclipse指定uat环境运行[在StartUpApplication.java启动环境的配置项中添加--spring.profiles.active=uat]
 *    3.直接在StartUpApplication主函数里面配置：
 *       SpringApplication app = new SpringApplication(StartUpApplication.class);
 *	     app.setAdditionalProfiles("uat");   //default dev 或uat
 *	     app.run(args);
 *	  4.seata分布式事务，采用druid动态代理方式，这里启动类需要排除掉自动配置数据库，后面会有地方单独配置
 *	  5.使用springBoot读取nacos配置时，StartUpApplication可以采用@NacosPropertySource(dataId = "boot-mapper", autoRefreshed = true)注解
 *	     读取配置采用peoperties，参考bootstrap.yml关于nacos的配置
 *	     添加依赖包
 *	     <dependency>
 *             <groupId>com.alibaba.boot</groupId>
 *             <artifactId>nacos-config-spring-boot-starter</artifactId>
 *             <version>0.2.7</version>
 *        </dependency>
 *	     @NacosValue(value = "${service.name:23}", autoRefreshed = true) 或者 @Value("${service.name:123}")
 *       private String serverName;
 *       读取nacos的远程配置信息
 *    6.使用springCloud读取nacos配置时，参考资料：https://www.cnblogs.com/larscheng/p/11392466.html
 *      读取配置采用peoperties，参考bootstrap.yml关于nacos的配置
 *       添加依赖包
 *        <dependency>
 *             <groupId>com.alibaba.cloud</groupId>
 *             <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
 *             <version>2.2.1.RELEASE</version>
 *         </dependency>
 *         <dependency>
 *             <groupId>com.alibaba.cloud</groupId>
 *             <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
 *             <version>2.2.1.RELEASE</version>
 *         </dependency>
 *        需要读取nacos配置的类上面加上@RefreshScope
 *        比如:   @RefreshScope
 *                public class SeataController {
 *                  	@Value("${service.name:123}")
 *                   	private String serverName;
 *                }
 *         读取远程nacos配置：https://github.com/nacos-group/nacos-examples
 */
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
//@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800,redisNamespace="bootsimple:spring:session")
@EnableJms
@EnableScheduling
@EnableFeignClients
@EnableDiscoveryClient
/*@NacosPropertySource(dataId = "boot-mapper", autoRefreshed = true)*/
public class StartUpApplication implements CommandLineRunner{

	final Logger log=LoggerFactory.getLogger(StartUpApplication.class);

	@Autowired
	ConfigurableEnvironment env;

	@Autowired
	InitConfiguration init;
	public static void main(String[] args) throws Exception {
		SpringApplication.run(StartUpApplication.class, args);
		//编码激活不同profile配置
		/*SpringApplication app = new SpringApplication(StartUpApplication.class);
		app.setAdditionalProfiles("uat");   //default dev 或uat
		app.run(args);*/
	}
	@Override
	public void run(String... args) throws Exception {
		String activeProfiles=StringUtils.arrayToCommaDelimitedString(env.getActiveProfiles());
		activeProfiles=StringUtils.isEmpty(activeProfiles)?"default":activeProfiles;
		log.info("===========系统启动完成！"+"运行环境:["+activeProfiles+"] IP:["+init.getServerIp()+"] PORT:["+init.getServerPort()+"]===========");
	}
	/*
	 * 获取服务器启动参数
	 */
	@Component
	public class InitConfiguration implements ApplicationListener<WebServerInitializedEvent> {
		private int serverPort;
		@Override
		public void onApplicationEvent(WebServerInitializedEvent event) {
			this.serverPort = event.getWebServer().getPort();
		}
		public int getServerPort() {
			return this.serverPort;
		}
		public String getServerIp() throws UnknownHostException {
			return InetAddress.getLocalHost().getHostAddress();
		}
	}

}
